using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using AvaloniaEdit;
using DebounceThrottle;
using System;

namespace AvaMaid.Neo.Views
{
    public partial class MiniDesignView : UserControl
    {
        private DebounceDispatcher _dispatcher = new DebounceDispatcher(TimeSpan.FromSeconds(1));

        public MiniDesignView()
        {
            InitializeComponent();
        }

        protected override void OnInitialized()
        {
            base.OnInitialized();
            var text = """
        <Grid>
            <TextBlock
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Text="Hello, Avalonia!" />
        </Grid>
        """;
 
            PART_TextEditor.Text = text;
        }

        private void TextEditor_TextChanged(object? sender, System.EventArgs e)
        {
            var textEditor = sender as TextEditor;
            if (textEditor is null) return;
            var text = textEditor.Text;

            UpdateView(text);
        }

        private void UpdateView(string text)
        {
            _dispatcher.Debounce(() =>
            {
                Dispatcher.UIThread.Invoke(() =>
                {
                    UpdateViewCore(text);
                });
            });
        }

        private void UpdateViewCore(string text)
        {
            var fullText = $@"
<UserControl xmlns='https://github.com/avaloniaui'>
{text}
</UserControl>";
            var userControl = AvaloniaRuntimeXamlLoader.Parse(fullText) as UserControl;
            PART_PrevPanel.Child = userControl;
        }

        protected override void OnLoaded(RoutedEventArgs e)
        {
            base.OnLoaded(e);

            string xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'>
<TextBlock Text='Hello, Avalonia!' />
</UserControl>";

            var userControl = AvaloniaRuntimeXamlLoader.Parse(xaml) as UserControl;

            //Content = userControl;  

        }
    }
}
